const express = require('express');
const router = express.Router();
const { PrismaClient } = require('@prisma/client');
const upload = require('../multer/multer');
const { returnUserInfo } = require('../utils/prismaData');
const { parseToken } = require('../utils/token');
const prisma = new PrismaClient()
/* GET users listing. */

// 查询用户展示信息
router.get('/user', upload.none(), async (req, res) => {
  const token = req.headers.authorization.split(' ')[1]
  const tokenData = await parseToken(token)
  if (!tokenData) return res.status(401).send({ msg: '登录过期' })
  const { id } = tokenData
  const { userId } = req.query
  if (!userId) return res.status(401).send({ msg: '错误的用户id' })
  const userData = await prisma.user.findUnique({
    where: {
      id: userId
    },
    select: {
      id: true,
      name: true,
      img: true,
      gender: true,
      email: true,
      prefer: true,
      bio: true,
      lastAt: true,
      registAt: true,
      tel: true,
      address: true,
      createColumn: {
        select: {
          id: true,
          name: true,
          mainPath: true,
          article: true,
          follow: true
        }
      },
      atricals: {
        where: {
          published: true
        },
        select: {
          id: true,
          title: true,
          createAt: true,
          content: true,
          published: true
        }
      },
      followed: true,
      followig: true,
    }
  })
  if (userData === null) return res.status(404).send({ msg: '获取错误' })
  const result = returnUserInfo(userData, id)
  res.status(200).send(result);
});

// 订阅用户
router.post('/like', upload.none(), async (req, res) => {
  const token = req.headers.authorization.split(' ')[1]
  const tokenData = await parseToken(token)
  if (!tokenData) return res.status(401).send({ msg: '登录过期' })
  const { id } = tokenData
  const { followerId, userId } = req.body
  if (id !== userId) return res.status(403).send({ msg: '错误的用户信息' })
  const followArticle = await prisma.followUser.upsert({
    where: {
      followigId_followedId: {
        followigId: followerId,
        followedId: id
      }
    },
    update: {},
    create: {
      followigId: followerId,
      followedId: id
    }
  })
  if (followArticle === null) res.status(401).send({ msg: '数据库操作错误' })
  res.status(200).send({ msg: '已添加到收藏' })
})

module.exports = router;
